package com.axones.planningpoker.rest.service;

import java.util.ArrayList;
import java.util.List;

import org.restlet.data.Status;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

import com.axones.planningpoker.bean.Item;
import com.axones.planningpoker.bean.Project;
import com.axones.planningpoker.bean.ProjectUser;
import com.axones.planningpoker.bean.User;
import com.axones.planningpoker.dao.ItemDAO;
import com.axones.planningpoker.dao.ProjectDAO;
import com.axones.planningpoker.dao.ProjectUserDAO;
import com.axones.planningpoker.dao.UserDAO;
import com.google.gson.Gson;

public class ProjectsResource extends ServerResource {
	private static ProjectDAO pDao;
	private static ProjectUserDAO puDao;
	private static ItemDAO iDao;
	private static UserDAO userDao;
	private static Gson gson;

	public ProjectsResource() {
		if (pDao == null) {
			pDao = new ProjectDAO();
		}
		if (puDao == null) {
			puDao = new ProjectUserDAO();
		}
		if (iDao == null) {
			iDao = new ItemDAO();
		}
		if (userDao == null) {
			userDao = new UserDAO();
		}
		if (gson == null) {
			gson = new Gson();
		}
	}

	@Get
	public String doGet() {
		Long id = Long.parseLong((String) getRequest().getAttributes()
				.get("id"));

		List<ProjectUser> projectUsers = puDao.getByUser(id);

		List<Project> projects = new ArrayList<Project>();

		for (ProjectUser projectUser : projectUsers) {
			Project project = getProject(projectUser.getProjectId());
			if (project != null) {
				project.setProfile(projectUser.getProfile());
				projects.add(project);
			}
		}

		setStatus(Status.SUCCESS_OK);

		return gson.toJson(projects);
	}
	
	private Project getProject(Long id){
		Project project = pDao.get(id);
		
		if(project == null){
			setStatus(Status.CLIENT_ERROR_NOT_FOUND);
			return null;
		}

		List<Item> items = iDao.getAll(id);
		List<ProjectUser> projectUsers = puDao.getByProject(id);
		List<User> users = new ArrayList<User>();

		for (ProjectUser pu : projectUsers) {
			User user = userDao.get(pu.getUserId());
			user.setProfile(pu.getProfile());
			users.add(user);
		}

		project.setItems(items);
		project.setUsers(users);
		
		return project;
	}
}
